<?php
/**
 * 春哥团队（www.cgtblog.com） - 春哥多端多商户万能DIY商城系统
 * Copyright © 2024 春哥技术团队 保留所有权利
 * =========================================================

 * ----------------------------------------------
 * 您只能在商业授权范围内使用，不可二次转售、分发、分享、传播
 * 任何企业和个人不得对代码以任何目的任何形式的再发布
 * =========================================================
 */

// +----------------------------------------------------------------------
// | 商城-商品管理
// +----------------------------------------------------------------------
namespace app\controller;
use think\facade\View;
use think\facade\Db;
use app\common\Wechat;
class ShopProduct extends Common
{
	//商品列表
    public function index(){
		if(request()->isAjax()){
			$page = input('param.page');
			$limit = input('param.limit');
			if(input('param.field') && input('param.order')){
				$order = input('param.field').' '.input('param.order');
			}else{
				$order = 'sort desc,id desc';
			}
			$where = array();
			$where[] = ['aid','=',aid];
			if(bid==0){
				if(input('param.bid')){
					$where[] = ['bid','=',input('param.bid')];
				}elseif(input('param.showtype')==2){
					$where[] = ['bid','>',0];
					$where[] = ['linkid','=',0];
                }elseif(input('param.showtype')=='all'){
                    $where[] = ['bid','>=',0];
				}elseif(input('param.showtype')==21){
					$where[] = ['bid','=',-1];
				}else{
					$where[] = ['bid','=',0];
				}
			}else{
				$where[] = ['bid','=',bid];
			}
			$where[] = ['douyin_product_id','=',''];
			if(input('?param.ischecked') && input('param.ischecked')!=='') $where[] = ['ischecked','=',$_GET['ischecked']];
			if(input('param.name')) $where[] = ['name','like','%'.$_GET['name'].'%'];
			if(input('?param.status') && input('param.status')!==''){
				$status = input('param.status');
				$nowtime = time();
				$nowhm = date('H:i');
				if($status==1){
					$where[] = Db::raw("`status`=1 or (`status`=2 and unix_timestamp(start_time)<=$nowtime and unix_timestamp(end_time)>=$nowtime) or (`status`=3 and ((start_hours<end_hours and start_hours<='$nowhm' and end_hours>='$nowhm') or (start_hours>=end_hours and (start_hours<='$nowhm' or end_hours>='$nowhm'))) )");
				}else{
					$where[] = Db::raw("`status`=0 or (`status`=2 and (unix_timestamp(start_time)>$nowtime or unix_timestamp(end_time)<$nowtime)) or (`status`=3 and ((start_hours<end_hours and (start_hours>'$nowhm' or end_hours<'$nowhm')) or (start_hours>=end_hours and (start_hours>'$nowhm' and end_hours<'$nowhm'))) )");
				}
			}
            if(input('?param.cid') && input('param.cid')!==''){
				$cid = input('param.cid');
				//子分类
				$clist = Db::name('shop_category')->where('aid',aid)->where('pid',$cid)->column('id');
				if($clist){
					$clist2 = Db::name('shop_category')->where('aid',aid)->where('pid','in',$clist)->column('id');
					$cCate = array_merge($clist, $clist2, [$cid]);
					if($cCate){
						$whereCid = [];
						foreach($cCate as $k => $c2){
							$whereCid[] = "find_in_set({$c2},cid)";
						}
						$where[] = Db::raw(implode(' or ',$whereCid));
					}
				} else {
					$where[] = Db::raw("find_in_set(".$cid.",cid)");
				}
			}
            if(input('?param.cid2') && input('param.cid2')!==''){
				$cid = input('param.cid2');
				//子分类
				$clist = Db::name('shop_category2')->where('aid',aid)->where('pid',$cid)->column('id');
				if($clist){
					$clist2 = Db::name('shop_category2')->where('aid',aid)->where('pid','in',$clist)->column('id');
					$cCate = array_merge($clist, $clist2, [$cid]);
					if($cCate){
						$whereCid = [];
						foreach($cCate as $k => $c2){
							$whereCid[] = "find_in_set({$c2},cid2)";
						}
						$where[] = Db::raw(implode(' or ',$whereCid));
					}
				} else {
					$where[] = Db::raw("find_in_set(".$cid.",cid2)");
				}
			}
			if(input('?param.gid') && input('param.gid')!=='') $where[] = Db::raw("find_in_set(".input('param.gid/d').",gid)");

			if(input('?param.wxvideo_status') && input('param.wxvideo_status')!==''){
				if(input('param.wxvideo_status') < 5){
					if(input('param.wxvideo_status') == 0){
						$where[] = ['wxvideo_product_id','=',''];
					}else{
						$where[] = ['wxvideo_edit_status','=',input('param.wxvideo_status')];
					}
				}else{
					$where[] = ['wxvideo_status','=',input('param.wxvideo_status')];
				}
			}
			$count = 0 + Db::name('shop_product')->where($where)->count();
			$data = Db::name('shop_product')->where($where)->page($page,$limit)->order($order)->select()->toArray();

			$cdata = Db::name('shop_category')->where('aid',aid)->column('name','id');
			if(bid > 0){
				$cdata2 = Db::name('shop_category2')->Field('id,name')->where('aid',aid)->where('bid',bid)->order('sort desc,id')->column('name','id');
			}
            $iscustomoption = 0;
			foreach($data as $k=>$v){
				$gglist = Db::name('shop_guige')->where('aid',aid)->where('proid',$v['id'])->select()->toArray();
				$ggdata = array();
				foreach($gglist as $gg){
					if($gg['stock']<$gg['stock_warning']){
						}else{
						$ggdata[] = $gg['name'].' × '.$gg['stock'] .' <button class="layui-btn layui-btn-xs layui-btn-disabled" style="color:#333">￥'.$gg['sell_price'].'</button>';
					}
				}
                $v['cid'] = explode(',',$v['cid']);
                $data[$k]['cname'] = null;
                if ($v['cid']) {
                    foreach ($v['cid'] as $cid) {
                        if($data[$k]['cname'])
                            $data[$k]['cname'] .= ' ' . $cdata[$cid];
                        else
                            $data[$k]['cname'] .= $cdata[$cid];
                    }
                }
				if($v['bid'] > 0){
					$v['cid2'] = explode(',',$v['cid2']);
					$data[$k]['cname2'] = null;
					if ($v['cid2']) {
						foreach ($v['cid2'] as $cid) {
							if($data[$k]['cname2'])
								$data[$k]['cname2'] .= ' ' . $cdata2[$cid];
							else
								$data[$k]['cname2'] .= $cdata2[$cid];
						}
					}
					$data[$k]['bname'] = Db::name('business')->where('aid',aid)->where('id',$v['bid'])->value('name');
				}else{
					$data[$k]['cname2'] = '';
					$data[$k]['bname'] = '平台自营';
				}
				$data[$k]['ggdata'] = implode('<br>',$ggdata);
				$sales_num = Db::name('shop_order_goods')->where('aid',aid)->where('proid',$v['id'])->where('status','in','1,2,3')->sum('num');
				$refund_num = Db::name('shop_refund_order_goods')
                    ->alias('rg')
                    ->join('shop_refund_order ro','rg.refund_orderid=ro.id')
                    ->where('rg.aid',aid)->where('rg.proid',$v['id'])->where('ro.refund_status',2)->sum('rg.refund_num');
                $realsalenum = $sales_num-$refund_num;
				$data[$k]['realsalenum'] = $realsalenum;
				if($v['status']==2){ //设置上架时间
					if(strtotime($v['start_time']) <= time() && strtotime($v['end_time']) >= time()){
						$data[$k]['status'] = 1;
					}else{
						$data[$k]['status'] = 0;
					}
				}
				if($v['status']==3){ //设置上架周期
					$start_time = strtotime(date('Y-m-d '.$v['start_hours']));
					$end_time = strtotime(date('Y-m-d '.$v['end_hours']));
					if(($start_time < $end_time && $start_time <= time() && $end_time >= time()) || ($start_time >= $end_time && ($start_time <= time() || $end_time >= time()))){
						$data[$k]['status'] = 1;
					}else{
						$data[$k]['status'] = 0;
					}
				}
				if($v['bid'] == -1) $data[$k]['sort'] = $v['sort'] - 1000000;
                $data[$k]['iscustomoption'] = $iscustomoption;
				}
			return json(['code'=>0,'msg'=>'查询成功','count'=>$count,'data'=>$data]);
		}
		//分类
		$clist = Db::name('shop_category')->Field('id,name')->where('aid',aid)->where('pid',0)->order('sort desc,id')->select()->toArray(); 
		foreach($clist as $k=>$v){
            $child = Db::name('shop_category')->Field('id,name')->where('aid',aid)->where('pid',$v['id'])->order('sort desc,id')->select()->toArray();
            foreach($child as $k2=>$v2){
                $child2 = Db::name('shop_category')->Field('id,name')->where('aid',aid)->where('pid',$v2['id'])->order('sort desc,id')->select()->toArray();
                $child[$k2]['child'] = $child2;
            }
            $clist[$k]['child'] = $child;
		}
		if(bid > 0){
			//商家的商品分类
			$clist2 = Db::name('shop_category2')->Field('id,name')->where('aid',aid)->where('bid',bid)->where('pid',0)->order('sort desc,id')->select()->toArray(); 
			foreach($clist2 as $k=>$v){
				$clist2[$k]['child'] = Db::name('shop_category2')->Field('id,name')->where('aid',aid)->where('pid',$v['id'])->order('sort desc,id')->select()->toArray(); 
			}
			View::assign('clist2',$clist2);
		}
		//分组
		$glist = Db::name('shop_group')->where('aid',aid)->order('sort desc,id')->select()->toArray();
		View::assign('clist',$clist);
		View::assign('glist',$glist);

		$fromwxvideo = input('param.fromwxvideo')==1?true:false;
		View::assign('fromwxvideo',$fromwxvideo);
		
		if($fromwxvideo){
			$rs = curl_post('https://api.weixin.qq.com/shop/account/get_brand_list?access_token='.Wechat::access_token(aid,'wx'),'{}');
			$rs = json_decode($rs,true);
			$brand_list = $rs['data'];
		}else{
			$brand_list = [];
		}

		if(session('BST_ID')){
			$userlist = Db::name('admin_user')->field('id,aid,un')->where('id','<>',$this->user['id'])->where('bid',0)->where('isadmin',1)->select()->toArray();
			View::assign('cancopy',true);
		}else{
			$userlist = [];
			View::assign('cancopy',false);
		}

        $default_cid = Db::name('member_level_category')->where('aid',aid)->where('isdefault', 1)->value('id');
        $default_cid = $default_cid ? $default_cid : 0;
		$levellist = Db::name('member_level')->where('aid',aid)->where('cid', $default_cid)->order('sort,id')->select()->toArray();
        View::assign('levellist',$levellist);
		$brand_list[] = ['brand_id'=>2100000000,'brand_wording'=>'无品牌'];
		View::assign('brand_list',$brand_list);
		View::assign('userlist',$userlist);
		View::assign('admin',$this->admin);
		return View::fetch();
    }
	//编辑商品
	public function edit(){
		if(input('param.id')){
			$info = Db::name('shop_product')->where('aid',aid)->where('id',input('param.id/d'))->find();
			if(!$info) showmsg('商品不存在');
			if(bid != 0 && $info['bid']!=bid) showmsg('无权限操作');
			if(bid != 0 && $info['linkid']!=0 && !getcustom('business_copy_product')) showmsg('无权限操作');
            $score_weishu = 0;
            }

		$usdrate = '0';
		$score_weishu = 0;
        //多规格
		$newgglist = array();
		if($info){
            $info['givescore'] = dd_money_format($info['givescore'],$score_weishu);
			$gglist = Db::name('shop_guige')->where('aid',aid)->where('proid',$info['id'])->select()->toArray();
			foreach($gglist as $k=>$v){
				$v['lvprice_data'] = json_decode($v['lvprice_data']);
                $v['givescore'] = dd_money_format($v['givescore'],$score_weishu);
				if($v['ks']!==null){
					$newgglist[$v['ks']] = $v;
				}else{
					Db::name('shop_guige')->where('aid',aid)->where('id',$v['id'])->update(['ks'=>$k]);
					$newgglist[$k] = $v;
				}
                $gglist[$k]['givescore'] = $v['givescore'];
			}
            $commissiondata3 = json_decode($info['commissiondata3'],true);
			foreach($commissiondata3 as $levelid=>$commission){
                $commissiondata3[$levelid]['commission1'] = dd_money_format($commission['commission1'],$score_weishu);
                $commissiondata3[$levelid]['commission2'] = dd_money_format($commission['commission2'],$score_weishu);
                $commissiondata3[$levelid]['commission3'] = dd_money_format($commission['commission3'],$score_weishu);
            }
            $info['commissiondata3'] = jsonEncode($commissiondata3);
		}
		//分类
		$clist = Db::name('shop_category')->Field('id,name')->where('aid',aid)->where('pid',0)->order('sort desc,id')->select()->toArray(); 
		foreach($clist as $k=>$v){
			$child = Db::name('shop_category')->Field('id,name')->where('aid',aid)->where('pid',$v['id'])->order('sort desc,id')->select()->toArray();
			foreach($child as $k2=>$v2){
				$child2 = Db::name('shop_category')->Field('id,name')->where('aid',aid)->where('pid',$v2['id'])->order('sort desc,id')->select()->toArray();
				$child[$k2]['child'] = $child2;
			}
			$clist[$k]['child'] = $child;
		}
		if(bid > 0){
			//商家的分类
			$clist2 = Db::name('shop_category2')->Field('id,name')->where('aid',aid)->where('bid',bid)->where('pid',0)->order('sort desc,id')->select()->toArray(); 
			foreach($clist2 as $k=>$v){
				$child = Db::name('shop_category2')->Field('id,name')->where('aid',aid)->where('bid',bid)->where('pid',$v['id'])->order('sort desc,id')->select()->toArray();
				foreach($child as $k2=>$v2){
					$child2 = Db::name('shop_category2')->Field('id,name')->where('aid',aid)->where('bid',bid)->where('pid',$v2['id'])->order('sort desc,id')->select()->toArray();
					$child[$k2]['child'] = $child2;
				}
				$clist2[$k]['child'] = $child;
			}
		}
		//分组
		$glist = Db::name('shop_group')->where('aid',aid)->order('sort desc,id')->select()->toArray();
		$freightdata = array();
		if($info && $info['freightdata']){
			$freightdata = Db::name('freight')->where('aid',aid)->where('id','in',$info['freightdata'])->order('sort desc,id')->select()->toArray();
		}

		$weightdata = array();
		$bset = Db::name('business_sysset')->where('aid',aid)->find();
		//分成结算类型
        $sysset = Db::name('admin_set')->where('aid',aid)->find();
        if($sysset['fxjiesuantype'] == 1) {
            $jiesuantypeDesc = '成交价';
        }elseif($sysset['fxjiesuantype'] == 2) {
            $jiesuantypeDesc = '销售利润';
        } else {
            $jiesuantypeDesc = '销售价';
        }

		if($info['showtj']) $info['showtj'] = explode(',',$info['showtj']);
		if($info['gettj']) $info['gettj'] = explode(',',$info['gettj']);
        if($info['cid']) $info['cid'] = explode(',',$info['cid']);
        if($info['cid2']) $info['cid2'] = explode(',',$info['cid2']);
        if($info['commission_mid'])  $info['commission_mid'] = $info['commission_mid'] ? json_decode($info['commission_mid'],true) : [];
		if($info['bid'] == -1) $info['sort'] = $info['sort'] - 1000000;
        $default_cid = Db::name('member_level_category')->where('aid',aid)->where('isdefault', 1)->value('id');
        $default_cid = $default_cid ? $default_cid : 0;
        if(false){}else {
            $aglevellist = Db::name('member_level')->where('aid',aid)->where('cid', $default_cid)->where('can_agent','<>',0)->order('sort,id')->select()->toArray();
            $levellist = Db::name('member_level')->where('aid',aid)->where('cid', $default_cid)->order('sort,id')->select()->toArray();
        }
		$gdlevellist = Db::name('member_level')->where('aid',aid)->where('cid', $default_cid)->where('fenhong','>','0')->order('sort,id')->select()->toArray();
		$teamlevellist = Db::name('member_level')->where('aid',aid)->where('cid', $default_cid)->where('teamfenhonglv','>','0')->order('sort,id')->select()->toArray();
		$areafhlevellist = Db::name('member_level')->where('aid',aid)->where('areafenhong','>','0')->select()->toArray();
        $gdlevellist_huiben = [];
		if($info['id']){
			$fuwulist = Db::name('shop_fuwu')->where('aid',aid)->where('bid',$info['bid'])->order('sort desc,id')->select()->toArray();
		}else{
			$fuwulist = Db::name('shop_fuwu')->where('aid',aid)->where('bid',bid)->order('sort desc,id')->select()->toArray();
		}
        //商品参数
		$parambid = bid;
		$whereParam = [];
        $whereParam[] = ['aid','=',aid];
        $whereParam[] = ['status','=',1];
        if($info['cid']){
            $whereCid = [];
            foreach($info['cid'] as $k => $c2){
                if($c2 == '') continue;
                $whereCid[] = "find_in_set({$c2},cid)";
            }
            if($whereCid){
				if(false){}else{
					$whereParam[] = ['bid','=',$parambid];
					$whereParam[] = Db::raw(implode(' or ',$whereCid). " or cid =''");
				}
            }else{
				$whereParam[] = ['bid','=',$parambid];
                $whereParam[] = Db::raw("cid =''");
			}
        }else{
			$whereParam[] = ['bid','=',$parambid];
            $whereParam[] = Db::raw(" cid =''");
        }
		$paramList = Db::name('shop_param')->where($whereParam)->order('sort desc,id')->select()->toArray();
//        dd($paramList);
		View::assign('paramList',$paramList);
	


		$paramdata = $info['paramdata'] ? json_decode($info['paramdata'],true) : [];
//        dd($paramdata);
        $auth = [];
        $info['paramdata'] = str_ireplace("'", "\'", $info['paramdata']);
        View::assign('fuwulist',$fuwulist);
		View::assign('aglevellist',$aglevellist);
		View::assign('levellist',$levellist);
		View::assign('gdlevellist',$gdlevellist);
        View::assign('gdlevellist_huiben',$gdlevellist_huiben);
		View::assign('teamlevellist',$teamlevellist);
		View::assign('areafhlevellist',$areafhlevellist);
		View::assign('info',$info);
		View::assign('newgglist',$newgglist);
		View::assign('clist',$clist);
		View::assign('clist2',$clist2);
		View::assign('glist',$glist);
		View::assign('freightdata',$freightdata);
		View::assign('bset',$bset);
        View::assign('jiesuantypeDesc',$jiesuantypeDesc);
		View::assign('paramdata',$paramdata);
		$fromwxvideo = input('param.fromwxvideo')==1?true:false;
		
		if($fromwxvideo){
			$rs = curl_post('https://api.weixin.qq.com/shop/account/get_brand_list?access_token='.Wechat::access_token(aid,'wx'),'{}');
			$rs = json_decode($rs,true);
			$brand_list = $rs['data'];
		}else{
			$brand_list = [];
		}
		$brand_list[] = ['brand_id'=>2100000000,'brand_wording'=>'无品牌'];
		View::assign('brand_list',$brand_list);
		View::assign('fromwxvideo',$fromwxvideo);
        View::assign('auth',$auth);
		
		$business_selfscore = 0;
		View::assign('business_selfscore',$business_selfscore);

        View::assign('sellpointTxt',$sellpointTxt);
		return View::fetch();
	}
    public function getParam()
    {
        $cid = input('post.cid');
        //商品参数
		$parambid = bid;
		$whereParam = [];
        $whereParam[] = ['aid','=',aid];
        $whereParam[] = ['status','=',1];
        if($cid){
            $cid = explode(',',$cid);
            $whereCid = [];
            foreach($cid as $k => $c2){
                $whereCid[] = "find_in_set({$c2},cid)";
            }
			if(false){}else{
				$whereParam[] = ['bid','=',$parambid];
				$whereParam[] = Db::raw(implode(' or ',$whereCid). " or cid =''");
			}
        }else{
			$whereParam[] = ['bid','=',$parambid];
            $whereParam[] = Db::raw(" cid =''");
        }

        $paramList = Db::name('shop_param')->where($whereParam)->order('sort desc,id')->select()->toArray();
        $paramList = $paramList ? $paramList : [];
//        dd($paramList);

        return json(['status'=>1,'msg'=>'操作成功','paramlist'=>$paramList]);
    }
	//保存商品
	public function save(){
		if(input('post.id')){
			$product = Db::name('shop_product')->where('aid',aid)->where('id',input('post.id/d'))->find();
			if(!$product) showmsg('商品不存在');
			if(bid != 0 && $product['bid']!=bid) showmsg('无权限操作');
		}
		$info = input('post.info/a');
		if(intval($info['sort']) >= 1000000) showmsg('商品序号不能大于1000000');

        $score_weishu = 0;
        if(bid > 0){
            $bset = Db::name('business_sysset')->where('aid',aid)->find();
        }
		$business_selfscore = 0;
		$info['detail'] = \app\common\Common::geteditorcontent($info['detail']);
		$data = array();
		$data['name'] = $info['name'];
		$data['pic'] = $info['pic'];
		$data['pics'] = $info['pics'];
        $data['diypics'] = $info['diypics'];
		$data['procode'] = $info['procode'];
		$data['sellpoint'] = $info['sellpoint'];
		$data['cid'] = $info['cid'];
		if(bid > 0){
			$data['cid2'] = $info['cid2'];
		}
        $data['price_type'] = $info['price_type'];
		$data['freighttype'] = $info['freighttype'];
		$data['freightdata'] = $info['freightdata'];
		$data['freightcontent'] = $info['freightcontent'];
		
        if(bid > 0 && $bset['commission_canset']!=1){
			$data['commissionset'] = -1;
        }else{
			$data['commissionset'] = $info['commissionset'];
		}
        $commissiondata3 = input('post.commissiondata3/a');
        foreach($commissiondata3 as $levelid=>$commission){
            $commissiondata3[$levelid]['commission1'] = dd_money_format($commission['commission1'],$score_weishu);
            $commissiondata3[$levelid]['commission2'] = dd_money_format($commission['commission2'],$score_weishu);
            $commissiondata3[$levelid]['commission3'] = dd_money_format($commission['commission3'],$score_weishu);
        }

		$data['commissiondata1'] = jsonEncode(input('post.commissiondata1/a'));
		$data['commissiondata2'] = jsonEncode(input('post.commissiondata2/a'));
		$data['commissiondata3'] = jsonEncode($commissiondata3);
        $data['commissiondata4'] = jsonEncode(input('post.commissiondata4/a'));
		$data['commissionset4'] = $info['commissionset4'];
		$data['lvprice'] = $info['lvprice'];
		$data['showtj'] = implode(',',$info['showtj']);
		$data['gettj'] = implode(',',$info['gettj']);

		//if(getcustom('product_glass') || getcustom('product_weight')){
		    $data['product_type'] = $info['product_type'];
        //}
        //购车基金
        //旅游基金
        //团队分红伯乐奖
        //加权分红状态
        //团队级差分红奖
        //团队级差分红奖
        if(bid == 0){
			$data['fenhongset'] = $info['fenhongset'];
			$data['gdfenhongset'] = $info['gdfenhongset'];
			$data['gdfenhongdata1'] = jsonEncode(input('post.gdfenhongdata1/a'));
			$data['gdfenhongdata2'] = jsonEncode(input('post.gdfenhongdata2/a'));
			$data['teamfenhongset'] = $info['teamfenhongset'];
			$data['teamfenhongdata1'] = jsonEncode(input('post.teamfenhongdata1/a'));
			$data['teamfenhongdata2'] = jsonEncode(input('post.teamfenhongdata2/a'));
			$data['areafenhongset'] = $info['areafenhongset'];
			$data['areafenhongdata1'] = jsonEncode(input('post.areafenhongdata1/a'));
			$data['areafenhongdata2'] = jsonEncode(input('post.areafenhongdata2/a'));
			}

		if(bid != 0){
			$bset = Db::name('business_sysset')->where('aid',aid)->find();
			if($bset['commission_canset']==0){
				$data['commissionset'] = '-1';
			}
            if($bset['product_showset']==0){
				$data['showtj'] = '-1';
				$data['gettj'] = '-1';
				$data['lvprice'] = 0;
			}
		}
		
		$data['video'] = $info['video'];
		$data['video_duration'] = $info['video_duration'];
		$data['perlimit'] = $info['perlimit'];
		$data['perlimitdan'] = $info['perlimitdan'];
		$data['limit_start'] = $info['limit_start'];
		if(bid == 0 || $business_selfscore == 1){
			$data['scoredkmaxset'] = $info['scoredkmaxset'];
			$data['scoredkmaxval'] = $info['scoredkmaxval'];
            $data['feepercent'] = $info['feepercent'] == '' || $info['feepercent'] < 0 ? null : $info['feepercent'];//商品独立抽成费率
		}
		
		if($info['oldsales'] != $info['sales']){
			$data['sales'] = $info['sales'];
		}
		$data['sort'] = $info['sort'];
		$data['status'] = $info['status'];
		$data['start_time'] = $info['start_time'];
		$data['end_time'] = $info['end_time'];
		$data['start_hours'] = $info['start_hours'];
		$data['end_hours'] = $info['end_hours'];

		$data['detail'] = $info['detail'];

		
		$data['sharetitle'] = $info['sharetitle'];
		$data['sharepic'] = $info['sharepic'];
		$data['sharedesc'] = $info['sharedesc'];
		$data['sharelink'] = $info['sharelink'];

		if($info['gid']){
			$data['gid'] = implode(',',$info['gid']);
		}else{
			$data['gid'] = '';
		}
		if($info['fwid']){
			$data['fwid'] = implode(',',$info['fwid']);
		}else{
			$data['fwid'] = '';
		}
		if(!$product) $data['createtime'] = time();
		$data['gettjtip'] = $info['gettjtip'];
		$data['gettjurl'] = $info['gettjurl'];

		$data['no_discount'] = $info['no_discount'];
        //会员等级限购
		if($info['wxvideo_third_cat_id']) $data['wxvideo_third_cat_id'] = $info['wxvideo_third_cat_id'];
		if($info['wxvideo_brand_id']) $data['wxvideo_brand_id'] = $info['wxvideo_brand_id'];
		if($info['wxvideo_qualification_pics']) $data['wxvideo_qualification_pics'] = $info['wxvideo_qualification_pics'];
        $data['fx_differential'] = $info['fx_differential'];

		if($info['lvprice']==1){
            $default_cid = Db::name('member_level_category')->where('aid',aid)->where('isdefault', 1)->value('id');
            $default_cid = $default_cid ? $default_cid : 0;
            $levellist = Db::name('member_level')->where('aid',aid)->where('cid', $default_cid)->order('sort,id')->select()->toArray();
			$defaultlvid = $levellist[0]['id'];
			$sellprice_field = 'sell_price_'.$defaultlvid;
		}else{
			$sellprice_field = 'sell_price';
		}
        $cost_bili = 0;
		$sell_price = 0;$market_price = 0;$cost_price = 0;$weight = 0;$givescore=0;$lvprice_data = [];$givetongzheng=0;
		foreach(input('post.option/a') as $ks=>$v){
			if($sell_price==0 || $v[$sellprice_field] < $sell_price){
				$sell_price = $v[$sellprice_field];
				$market_price = $v['market_price'];
				$cost_price = $v['cost_price'];
				if($cost_price<=0 && $cost_bili>0){
                    $cost_price = bcmul($sell_price,$cost_bili/100,2);
                }
				$givescore = dd_money_format($v['givescore'],$score_weishu);
				$weight = $v['weight'];
				if($info['lvprice']==1){
					$lvprice_data = [];
					foreach($levellist as $lv){
						$lvprice_data[$lv['id']] = $v['sell_price_'.$lv['id']];
					}
				}
			}
		}
		if($info['lvprice']==1){
			$data['lvprice_data'] = json_encode($lvprice_data);
		}
		$data['market_price'] = $market_price;
		$data['cost_price'] = $cost_price;
		$data['sell_price'] = $sell_price;
		$data['givescore'] = dd_money_format($givescore,$score_weishu);
		$data['weight'] = $weight;
		$data['stock'] = 0;
		foreach(input('post.option/a') as $v){
			$data['stock'] += $v['stock'];
		}
		//多规格 规格项
		$data['guigedata'] = input('post.specs');

		$data['paramdata'] = jsonEncode(input('post.paramdata/a'));

		if(bid !=0 ){
			$bset = Db::name('business_sysset')->where('aid',aid)->find();
			if($bset['product_check'] == 1){
				$data['ischecked'] = 0;
			}
            }
		if($product){
			if($product['bid'] == -1) $data['sort'] = 1000000 + intval($data['sort']);
			Db::name('shop_product')->where('aid',aid)->where('id',$product['id'])->update($data);
			$proid = $product['id'];
			\app\common\System::plog('商城商品编辑'.$proid);
		}else{
			$data['aid'] = aid;
			$data['bid'] = bid;
			if(bid == 0 && $info['bid']){
				$data['bid'] = $info['bid'];
				if($info['bid'] == -1) $data['sort'] = 1000000 + intval($data['sort']);
			}
			$proid = Db::name('shop_product')->insertGetId($data);
			\app\common\System::plog('商城商品编辑'.$proid);
		}

		if($product){
            $bid = $product['bid'];
        }else{
            $bid = $info['bid']?:bid;
        }
        //更新商户虚拟销量
        $sales = $info['sales']-$info['oldsales'];
		if($sales!=0){
            \app\model\Payorder::addSales(0,'sales',aid,$bid,$sales);
        }

		//dump(input('post.option/a'));die;
		//多规格
		$newggids = array();
		foreach(input('post.option/a') as $ks=>$v){
			$ggdata = array();
			$ggdata['proid'] = $proid;
			$ggdata['ks'] = $ks;
			$ggdata['name'] = $v['name'];
			$ggdata['pic'] = $v['pic'] ? $v['pic'] : '';
			$ggdata['market_price'] = $v['market_price']>0 ? $v['market_price']:0;
			$cost_price = $v['cost_price']>0 ? $v['cost_price']:0;
			if($cost_price<=0 && $cost_bili>0){
                $cost_price = bcmul($v['sell_price'],$cost_bili/100,2);
            }
            $ggdata['cost_price'] = $cost_price;
            $ggdata['sell_price'] = $v['sell_price']>0 ? $v['sell_price']:0;
			$ggdata['weight'] = $v['weight']>0 ? $v['weight']:0;
			$ggdata['procode'] = $info['procode'];
			$ggdata['barcode'] = $v['barcode'];
			$ggdata['givescore'] = dd_money_format($v['givescore'],$score_weishu);
            $ggdata['stock'] = $v['stock']>0 ? $v['stock']:0;
            $ggdata['limit_start'] = $v['limit_start']>0 ? $v['limit_start']:0;
			
			$lvprice_data = [];
			if($info['lvprice']==1){
				$ggdata['sell_price'] = $v['sell_price_'.$levellist[0]['id']]>0 ? $v['sell_price_'.$levellist[0]['id']]:0;
				foreach($levellist as $lv){
					$sell_price = $v['sell_price_'.$lv['id']]>0 ? $v['sell_price_'.$lv['id']]:0;
					$lvprice_data[$lv['id']] = $sell_price;
				}
				$ggdata['lvprice_data'] = json_encode($lvprice_data);
			}

			$guige = Db::name('shop_guige')->where('aid',aid)->where('proid',$proid)->where('ks',$ks)->find();
			if($guige){
				Db::name('shop_guige')->where('aid',aid)->where('id',$guige['id'])->update($ggdata);
				$ggid = $guige['id'];
			}else{
				$ggdata['aid'] = aid;
				$ggid = Db::name('shop_guige')->insertGetId($ggdata);
			}
			$newggids[] = $ggid;
		}
		Db::name('shop_guige')->where('aid',aid)->where('proid',$proid)->where('id','not in',$newggids)->delete();
		
		$this->tongbuproduct($proid);

		\app\common\Wxvideo::updateproduct($proid);
		
		return json(['status'=>1,'msg'=>'操作成功','url'=>(string)url('index')]);
	}
	//改价格
	public function changeprice(){
		$proid = input('post.proid/d');
		$product = Db::name('shop_product')->where('aid',aid)->where('id',$proid)->find();
		if(!$product) showmsg('商品不存在');
		if(bid != 0 && $product['bid']!=bid) showmsg('无权限操作');

		if($product['lvprice']==1){
            $default_cid = Db::name('member_level_category')->where('aid',aid)->where('isdefault', 1)->value('id');
            $default_cid = $default_cid ? $default_cid : 0;
            $levellist = Db::name('member_level')->where('aid',aid)->where('cid', $default_cid)->order('sort,id')->select()->toArray();
			$defaultlvid = $levellist[0]['id'];
			$sellprice_field = 'sell_price_'.$defaultlvid;
		}else{
			$sellprice_field = 'sell_price';
		}

		$sell_price = 0;$market_price = 0;$cost_price = 0;$lvprice_data = [];
		foreach(input('post.option/a') as $ks=>$v){
			if($sell_price==0 || $v[$sellprice_field] < $sell_price){
				$sell_price = $v[$sellprice_field];
				$market_price = $v['market_price'];
				$cost_price = $v['cost_price'];
				if($product['lvprice']==1){
					$lvprice_data = [];
					foreach($levellist as $lv){
						$lvprice_data[$lv['id']] = $v['sell_price_'.$lv['id']];
					}
				}
			}
		}
		$data = [];
		if($product['lvprice']==1){
			$data['lvprice_data'] = json_encode($lvprice_data);
		}
		$data['market_price'] = $market_price;
		$data['cost_price'] = $cost_price;
		$data['sell_price'] = $sell_price;
		$data['stock'] = 0;
		foreach(input('post.option/a') as $v){
			$data['stock'] += $v['stock'];
		}
		Db::name('shop_product')->where('aid',aid)->where('id',$proid)->update($data);
		foreach(input('post.option/a') as $ks=>$v){
			$ggdata = [];
			$ggdata['market_price'] = $v['market_price']>0 ? $v['market_price']:0;
			$ggdata['cost_price'] = $v['cost_price']>0 ? $v['cost_price']:0;
			$ggdata['sell_price'] = $v['sell_price']>0 ? $v['sell_price']:0;
			$ggdata['stock'] = $v['stock']>0 ? $v['stock']:0;
			$lvprice_data = [];
			if($product['lvprice']==1){
				$ggdata['sell_price'] = $v['sell_price_'.$levellist[0]['id']]>0 ? $v['sell_price_'.$levellist[0]['id']]:0;
				foreach($levellist as $lv){
					$sell_price = $v['sell_price_'.$lv['id']]>0 ? $v['sell_price_'.$lv['id']]:0;
					$lvprice_data[$lv['id']] = $sell_price;
				}
				$ggdata['lvprice_data'] = json_encode($lvprice_data);
			}
			Db::name('shop_guige')->where('aid',aid)->where('id',$v['ggid'])->update($ggdata);
		}
		\app\common\Wxvideo::update_without_audit($proid);

		return json(['status'=>1,'msg'=>'操作成功']);
	}
	//改状态
	public function setst(){
		$st = input('post.st/d');
		$ids = input('post.ids/a');
		$where = [];
		$where[] = ['aid','=',aid];
		$where[] = ['id','in',$ids];
		if(bid !=0){
			$where[] = ['bid','=',bid];
            if(!getcustom('business_copy_product')) {
                $where[] = ['linkid', '=', 0];
            }
		}
		Db::name('shop_product')->where($where)->update(['status'=>$st]);
		
		$this->tongbuproduct($ids);
		if($st == 0){
			\app\common\Wxvideo::delisting($ids);
		}else{
			\app\common\Wxvideo::listing($ids);
		}
		\app\common\System::plog('商城商品改状态'.implode(',',$ids));
		return json(['status'=>1,'msg'=>'操作成功']);
	}
	//审核
	public function setcheckst(){
		$st = input('post.st/d');
		$id = input('post.id/d');
		$reason = input('post.reason');
		Db::name('shop_product')->where('aid',aid)->where('id',$id)->update(['ischecked'=>$st,'check_reason'=>$reason]);
		return json(['status'=>1,'msg'=>'操作成功']);
	}
	//删除
	public function del(){
		$ids = input('post.ids/a');
		if(!$ids) $ids = array(input('post.id/d'));
		$where = [];
		$where[] = ['aid','=',aid];
		$where[] = ['id','in',$ids];
		if(bid !=0){
			$where[] = ['bid','=',bid];
			if(!getcustom('business_copy_product')){
                $where[] = ['linkid','=',0];
            }
		}
		$prolist = Db::name('shop_product')->where($where)->select();
		foreach($prolist as $pro){
			Db::name('shop_product')->where('id',$pro['id'])->delete();
			Db::name('shop_guige')->where('proid',$pro['id'])->delete();
			if($pro['wxvideo_product_id']){
                \app\common\Wxvideo::deleteproduct($pro['id']);
            }
		}
		\app\common\System::plog('商城商品删除'.implode(',',$ids));
		return json(['status'=>1,'msg'=>'删除成功']);
	}
	//复制商品
	public function procopy(){
        $where = [];
        if(bid > 0){
            $where[] = ['bid','=',bid];
        }
		$product = Db::name('shop_product')->where('aid',aid)->where($where)->where('id',input('post.id/d'))->find();
		if(!$product) return json(['status'=>0,'msg'=>'商品不存在,请重新选择']);
		$gglist = Db::name('shop_guige')->where('aid',aid)->where('proid',$product['id'])->select()->toArray();
		$data = $product;
		$data['name'] = '复制-'.$data['name'];
        if($data['detail']){
            //处理tab组件
            $detail = json_decode($data['detail'],true);
            if($detail){
                foreach ($detail as $k => $item){
                    if($item['temp'] == 'tab'){
                        $detail[$k]['id'] = $item['id'].rand(0,9999);
                        $tablist = Db::name('designerpage_tab')->where('aid',aid)->where('tabid',$item['id'])->select()->toArray();
                        if($tablist){
                            foreach ($tablist as $k2 => $item2){
                                unset($item2['id']);
                                $item2['tabid'] = $detail[$k]['id'];
                                Db::name('designerpage_tab')->insert($item2);
                            }
                        }
                    }
                }
                $data['detail'] = json_encode($detail);
            }
        }
		unset($data['id']);
		unset($data['wxvideo_product_id']);
		unset($data['wxvideo_edit_status']);
		unset($data['wxvideo_status']);
		unset($data['wxvideo_reject_reason']);
		$data['status'] = 0;
		$newproid = Db::name('shop_product')->insertGetId($data);
		foreach($gglist as $gg){
			$ggdata = $gg;
			$ggdata['proid'] = $newproid;
			unset($ggdata['id']);
			unset($ggdata['linkid']);
			Db::name('shop_guige')->insert($ggdata);
		}
		$this->tongbuproduct($newproid);
		\app\common\System::plog('商城商品复制'.$newproid);
		return json(['status'=>1,'msg'=>'复制成功','proid'=>$newproid]);
	}
	//获取分类信息
	public function getcategory(){
		if(!session('BST_ID')) return json(['status'=>0,'msg'=>'无权限操作']);
		$toaid = input('param.toaid/d');
		//分类
		$clist = Db::name('shop_category')->Field('id,name')->where('aid',$toaid)->where('pid',0)->order('sort desc,id')->select()->toArray(); 
		foreach($clist as $k=>$v){
			$child = Db::name('shop_category')->Field('id,name')->where('aid',$toaid)->where('pid',$v['id'])->order('sort desc,id')->select()->toArray();
			foreach($child as $k2=>$v2){
				$child2 = Db::name('shop_category')->Field('id,name')->where('aid',$toaid)->where('pid',$v2['id'])->order('sort desc,id')->select()->toArray();
				$child[$k2]['child'] = $child2;
			}
			$clist[$k]['child'] = $child;
		}
		return json(['status'=>1,'data'=>$clist]);
	}
	//复制到其他账号商品
	public function userProcopy(){
        set_time_limit(0);
        ini_set('memory_limit',-1);
		if(!session('BST_ID')) return json(['status'=>0,'msg'=>'无权限操作']);
		$ids = input('post.ids/a');
        $togroupid = input('param.togroupid');
		$toaid = input('param.toaid');
		$tocid = input('param.tocid');
		if(!$toaid && !$togroupid) return json(['status'=>0,'msg'=>'请选择账号']);
		if(!$tocid && !$togroupid) return json(['status'=>0,'msg'=>'请选择分类']);
		if(!$ids) $ids = array(input('post.id/d'));
		$where = [];
		$where[] = ['aid','=',aid];
		//$where[] = ['bid','=',bid];
		$where[] = ['id','in',$ids];
		$prolist = Db::name('shop_product')->where($where)->select()->toArray();
		if(!$prolist) return json(['status'=>0,'msg'=>'商品不存在,请重新选择']);

        if(!$toaid && $togroupid){
            }else{
            $toaidArr = [$toaid];
        }

		foreach($prolist as $product){
			$gglist = Db::name('shop_guige')->where('aid',aid)->where('proid',$product['id'])->select()->toArray();
			$data = $product;
            foreach ($toaidArr as $toaid){
                $data['aid'] = $toaid;
                $data['bid'] = 0;
                $data['name'] = $data['name'];
                $data['cid'] = $tocid;
                //$data['status'] = 0;
                unset($data['id']);
                unset($data['wxvideo_product_id']);
                unset($data['wxvideo_edit_status']);
                unset($data['wxvideo_status']);
                unset($data['wxvideo_reject_reason']);
                unset($data['gid']);
                if($data['detail']){
                    //处理tab组件
                    $detail = json_decode($product['detail'],true);
                    if($detail){
                        foreach ($detail as $k => $item){
                            if($item['temp'] == 'tab'){
                                $detail[$k]['id'] = 'M'.time().rand(1000,9999);
                                $tablist = Db::name('designerpage_tab')->where('aid',aid)->where('tabid',$item['id'])->select()->toArray();
                                if($tablist){
                                    foreach ($tablist as $k2 => $item2){
                                        unset($item2['id']);
                                        $item2['aid'] = $toaid;
                                        $item2['tabid'] = $detail[$k]['id'];
                                        Db::name('designerpage_tab')->insert($item2);
                                    }
                                }
                            }
                        }
                        $data['detail'] = json_encode($detail);
                    }
                }
                $newproid = Db::name('shop_product')->insertGetId($data);
                foreach($gglist as $gg){
                    $ggdata = $gg;
                    $ggdata['proid'] = $newproid;
                    $ggdata['aid'] = $toaid;
                    unset($ggdata['id']);
                    unset($ggdata['linkid']);
                    Db::name('shop_guige')->insert($ggdata);
                }
            }
		}
		//$msg = '商城商品复制到账号'.input('post.userid/d').'/'.implode(',',$ids);
		//\app\common\System::plog($msg);
		return json(['status'=>1,'msg'=>'复制成功']);
	}
	//导入商品
	public function importexcel(){
		set_time_limit(0);
		ini_set('memory_limit',-1);
		$file = input('post.file');
		if(!$file) return json(['status'=>0,'msg'=>'请上传excel文件']);
		$exceldata = $this->import_excel($file);
        $data_count = count($exceldata);
		$cateArr = Db::name('shop_category')->where('aid',aid)->column('name','id');
		$cateArr = array_flip($cateArr);
		$groupArr = Db::name('shop_group')->where('aid',aid)->column('name','id');
		$groupArr = array_flip($groupArr);
		$fuwuArr = Db::name('shop_fuwu')->where('aid',aid)->column('name','id');
		$fuwuArr = array_flip($fuwuArr);

        $pagenum = input('pagenum')?:1;
        $pagelimit = input('pagelimit')?:5;
        $start_hange = ($pagenum-1)*$pagelimit+1;
        $end_hang = $pagenum*$pagelimit;

		$insertnum = 0;
		$updatenum = 0;
		foreach($exceldata as $hang=>$data){
            if($hang+1<$start_hange){
                continue;
            }
            if($hang+1>$end_hang){
                continue;
            }
			$indata = [];
			$indata['aid'] = aid;
			$indata['bid'] = bid;
			$indata['name'] = $data[0];
			
			$pic = $data[1];
			if(strpos($pic,'//')===0) $pic = 'https:'.$pic;
			if($pic){
				$pic = \app\common\Pic::uploadoss($pic);
			}
			$indata['pic'] = $pic;

			$pics = [];
			if($data[2]){
				foreach(explode(',',$data[2]) as $v){
					$pic = $v;
					if(strpos($pic,'//')===0) $pic = 'https:'.$pic;
					if($pic){
						$pic = \app\common\Pic::uploadoss($pic);
					}
					$pics[] = $pic;
				}
			}

			$indata['pics'] = implode(',',$pics);
			$indata['sellpoint'] = $data[3];
			if($data[4]){
				$cids = [];
				foreach(explode(',',$data[4]) as $v){
					if(!$cateArr[$v]){
						if(bid == 0){
							$cid = Db::name('shop_category')->insertGetId(['aid'=>aid,'name'=>$v,'sort'=>0]);
							$cids[] = $cid;
							$cateArr[$v] = $cid;
						}
					}else{
						$cids[] = $cateArr[$v];
					}
				}
				$indata['cid'] = implode(',',$cids);
			}
			if($data[5]){
				$gids = [];
				foreach(explode(',',$data[5]) as $v){
					if(!$groupArr[$v]){
						if(bid == 0){
							$gid = Db::name('shop_group')->insertGetId(['aid'=>aid,'name'=>$v,'sort'=>0]);
							$gids[] = $gid;
							$groupArr[$v] = $gid;
						}
					}else{
						$gids[] = $groupArr[$v];
					}
				}
				$indata['gid'] = implode(',',$gids);
			}
			if($data[6]){
				$fwids = [];
				foreach(explode(',',$data[6]) as $v){
					if(!$fuwuArr[$v]){
						$fwid = Db::name('shop_fuwu')->insertGetId(['aid'=>aid,'bid'=>bid,'name'=>$v,'sort'=>0]);
						$fuwuArr[$v] = $fwid;
					}else{
						$fwid = $fuwuArr[$v];
					}
					$fwids[] = $fwid;
				}
				$indata['fwid'] = implode(',',$fwids);
			}
			$indata['procode'] = $data[7];
			$indata['guigedata'] = '[{"k":0,"title":"规格","items":[{"k":0,"title":"默认规格"}]}]';
			$indata['market_price'] = round($data[8],2);
			$indata['cost_price'] = round($data[9],2);
			$indata['sell_price'] = round($data[10],2);
			$indata['weight'] = intval($data[11]);
			$indata['stock'] = intval($data[12]);
			$indata['sales'] = intval($data[13]);
			if($data[14] == '已上架' || $data[14] == '上架'){
				$indata['status'] = 1;
			}else{
				$indata['status'] = 0;
			}
			$indata['detail'] = jsonEncode([[
				'id'=>'M0000000000000',
				'temp'=>'richtext',
				'params'=>['bgcolor'=>'#FFFFFF','margin_x'=>0,'margin_y'=>0,'padding_x'=>0,'padding_y'=>0,'quanxian'=>['all'=>true],'platform'=>['all'=>true]],
				'data'=>'',
				'other'=>'',
				'content'=>$data[15]
			]]);
			$indata['createtime'] = time();
			if(bid != 0) $indata['commissionset'] = -1;
			$proid = Db::name('shop_product')->insertGetId($indata);
			$ggdata = [];
			$ggdata['aid'] = aid;
			$ggdata['proid'] = $proid;
			$ggdata['name'] = $indata['name'];
			$ggdata['pic'] = $indata['pic'];
			$ggdata['cost_price'] = $indata['cost_price'];
			$ggdata['market_price'] = $indata['market_price'];
			$ggdata['sell_price'] = $indata['sell_price'];
			$ggdata['stock'] = $indata['stock'];
			$ggdata['weight'] = $indata['weight'];
			$ggdata['ks'] = 0;
			Db::name('shop_guige')->insert($ggdata);

            //更新商户虚拟销量
            $sales = $indata['sales'];
            if($sales!=0){
                \app\model\Payorder::addSales(0,'sales',aid,bid,$sales);
            }


			$insertnum++;
		}
		\app\common\System::plog('导入商品');
        $suc_total = $pagelimit*($pagenum-1)+$insertnum;
        $status = 1;
        if($suc_total>=$data_count){
            $status = 2;
        }
        $remain = $data_count-$suc_total;
        return json(['status'=>$status,'msg'=>'成功导入'.$suc_total.'条数据,剩余'.$remain]);
	}
	//同步商品到商户
	private function tongbuproduct($proids){
		}

	//选择商品
	public function chooseproduct(){
		//分类
		$clist = Db::name('shop_category')->Field('id,name')->where('aid',aid)->where('pid',0)->order('sort desc,id')->select()->toArray(); 
		foreach($clist as $k=>$v){
			$clist[$k]['child'] = Db::name('shop_category')->Field('id,name')->where('aid',aid)->where('pid',$v['id'])->order('sort desc,id')->select()->toArray(); 
		}
		//分组
		$glist = Db::name('shop_group')->where('aid',aid)->order('sort desc,id')->select()->toArray();
		//商户
		$blist = Db::name('business')->where('aid',aid)->order('sort desc,id desc')->select()->toArray();
		View::assign('blist',$blist);
		View::assign('clist',$clist);
		View::assign('glist',$glist);
		return View::fetch();
	}
	//获取商品信息
	public function getproduct(){
		$proid = input('post.proid/d');
		$product = Db::name('shop_product')->where('aid',aid)->where('id',$proid)->find();
		//多规格
		$newgglist = array();
		$gglist = Db::name('shop_guige')->where('aid',aid)->where('proid',$product['id'])->select()->toArray();
		foreach($gglist as $k=>$v){
            $newgglist[$v['ks']] = $v;
		}
		$guigedata = json_decode($product['guigedata']);
		return json(['product'=>$product,'gglist'=>$newgglist,'guigedata'=>$guigedata]);
	}

	//上传商品到视频号
	public function towxvideo(){
		$proids = input('param.ids/a');
		$prolist = Db::name('shop_product')->where('aid',aid)->where('bid',0)->where('id','in',$proids)->where('wxvideo_status',0)->select()->toArray();
		if(!$prolist) return json(['status'=>0,'msg'=>'不存在未上传的商品']);

		$third_cat_id = input('param.third_cat_id');
		$brand_id = input('param.brand_id');
		$qualification_pics = input('param.qualification_pics');
		$update = [];
		$update['wxvideo_third_cat_id'] = $third_cat_id;
		$update['wxvideo_brand_id'] = $brand_id;
		$update['wxvideo_product_id'] = $product_id;
		if($qualification_pics){
			$update['wxvideo_qualification_pics'] = $qualification_pics;
		}
		Db::name('shop_product')->where('bid',0)->where('id','in',$proids)->where('wxvideo_status',0)->update($update);

		$errmsg = '';
		$successnum = 0;
		$errnum = 0;
		foreach($prolist as $product){
			$rs = \app\common\Wxvideo::updateproduct($product['id']);
			if($rs['status'] == 1){
				$successnum++;
			}else{
				$errnum++;
				$errmsg = $rs['msg'];
			}
		}
		if($errnum == 0){
			return json(['status'=>1,'msg'=>'成功同步商品'.$successnum.'个']);
		}else{
			return json(['status'=>0,'msg'=>'成功'.$successnum.'个,失败'.$errnum.'个,原因:'.$errmsg]);
		}
		
	}
	//更新视频号商品状态
	public function wxvideoupdatest(){
		$url = 'https://api.weixin.qq.com/shop/spu/get_list?access_token='.Wechat::access_token(aid,'wx');
		$prolist = [];
		$postdata = [];
		$postdata['page'] = 1;
		$postdata['page_size'] = 100;
		$rs = curl_post($url,jsonEncode($postdata));
		$rs = json_decode($rs,true);
		if($rs['errcode']!=0){
			return json(['status'=>0,'msg'=>Wechat::geterror($rs),'$postdata'=>$postdata]);
		}
		$totalnum = $rs['total_num'];
		$prolist = array_merge($prolist,$rs['spus']);
		if($totalnum > 100){
			$pagecount = ceil($totalnum / 100);
			for($i=1;$i<$pagecount;$i++){
				$postdata = [];
				$postdata['page'] = $i+1;
				$postdata['page_size'] = 100;
				$rs = curl_post($url,jsonEncode($postdata));
				$rs = json_decode($rs,true);
				if($rs['spus']){
					$prolist = array_merge($prolist,$rs['spus']);
				}
			}
		}
		foreach($prolist as $pro){
			$product = Db::name('shop_product')->where('wxvideo_product_id',$pro['product_id'])->find();
			if(!$product){
				curl_post('https://api.weixin.qq.com/shop/spu/del?access_token='.Wechat::access_token(aid,'wx'),jsonEncode(['product_id'=>$pro['product_id']]));
				continue;
			}
			$wxvideo_reject_reason = $pro['audit_info']['reject_reason'];
			if($pro['edit_status'] != $v['wxvideo_edit_status'] || $pro['status'] != $v['wxvideo_status']){
				Db::name('shop_product')->where('id',$product['id'])->update(['wxvideo_edit_status'=>$pro['edit_status'],'wxvideo_status'=>$pro['status'],'wxvideo_reject_reason'=>$wxvideo_reject_reason]);
			}
		}
		return json(['status'=>1,'msg'=>'同步更新完成']);
	}

	//撤回审核
	public function wxvideo_del_audit(){
		$proid = input('param.proid/d');
		$product = Db::name('shop_product')->where('aid',aid)->where('id',$proid)->find();
		$rs = curl_post('https://api.weixin.qq.com/shop/spu/del_audit?access_token='.Wechat::access_token(aid,'wx'),jsonEncode(['product_id'=>$product['wxvideo_product_id']]));
		$rs = json_decode($rs,true);
		if($rs['errcode']!=0){
			return json(['status'=>0,'msg'=>Wechat::geterror($rs)]);
		}else{
			Db::name('shop_product')->where('aid',aid)->where('id',$proid)->update(['wxvideo_edit_status'=>1]);
			return json(['status'=>1,'msg'=>'操作成功']);
		}
	}
	//视频号上架
	public function wxvideo_listing(){
		$proid = input('param.proid/d');
		$rs = \app\common\Wxvideo::listing($proid);
		return json($rs);
	}
	//视频号下架
	public function wxvideo_delisting(){
		$proid = input('param.proid/d');
		$rs = \app\common\Wxvideo::delisting($proid);
		return json($rs);
	}
	
	//规格拆分
	public function getsplitdata(){
		$proid = input('post.proid');
		$splitlist = Db::name('shop_ggsplit')->where('aid',aid)->where('proid',$proid)->select()->toArray();
		$gglist = Db::name('shop_guige')->where('aid',aid)->where('proid',$proid)->select()->toArray();
		if(!$splitlist) $splitlist = [['ggid1'=>'','ggid2'=>'','multiple'=>'']];
		return json(['splitlist'=>$splitlist,'gglist'=>$gglist]);
	}
	public function ggsplit(){
		//var_dump(input('post.'));
		$proid = input('post.proid/d');
		if(!$proid) return json(['status'=>0,'msg'=>'获取商品信息失败']);
		$ggid1Arr = input('post.ggid1/a');
		$ggid2Arr = input('post.ggid2/a');
		$multipleArr = input('post.multiple/a');
		$datalist = [];
		foreach($ggid1Arr as $k=>$v){
			if($ggid1Arr[$k] == '' || $ggid2Arr[$k] == '') continue;
			$data = [];
			$data['aid'] = aid;
			$data['proid'] = $proid;
			$data['ggid1'] = $ggid1Arr[$k];
			$data['ggid2'] = $ggid2Arr[$k];
			$data['multiple'] = $multipleArr[$k];
			$data['createtime'] = time();
			$datalist[$data['ggid1'].'-'.$data['ggid2']] = $data;
			if(!$multipleArr[$k] || $multipleArr[$k] <=0) return json(['status'=>0,'msg'=>'倍数必须是大于0的整数']);
			if($data['ggid1'] == $data['ggid2']) return json(['status'=>0,'msg'=>'不能设置两个相同的规格进行拆分']);
		}
		Db::name('shop_ggsplit')->where('aid',aid)->where('proid',$proid)->delete();
		foreach($datalist as $k=>$data){
			Db::name('shop_ggsplit')->insert($data);
		}
		\app\model\ShopProduct::calculateStock($proid);
		return json(['status'=>1,'msg'=>'设置成功','url'=>true]);
	}
	
	//锁定
	public function dolock(){
		if(session('IS_ADMIN') == 0) return json(['status'=>1,'msg'=>'无权限操作']);
		$id = input('post.id/d');
		$st = input('post.st/d');
		Db::name('shop_product')->where('aid',aid)->where('id',$id)->update(['islock'=>$st]);
		return json(['status'=>1,'msg'=>'操作成功']);
	}

	public function jsttongbu(){  //聚水潭商品同步
        }


    //导入商品
    public function importexcelnew(){

        set_time_limit(0);
        ini_set('memory_limit',-1);
        $file = input('post.file');
        if(!$file) return json(['status'=>0,'msg'=>'请上传excel文件']);
        $exceldata = $this->import_excel($file);
        foreach($exceldata as $k=>$v){
            if(empty(array_filter($v))){
                unset($exceldata[$k]);
            }
        }
        $exceldata = array_values($exceldata);
        if(bid > 0){
            $cateArr = Db::name('shop_category2')->Field('id,name')->where('aid',aid)
                ->where('bid',bid)->column('name','id');
        }else{
            $cateArr = Db::name('shop_category')->where('aid',aid)->column('name','id');
        }
        $cateArr = array_flip($cateArr);

        $groupArr = Db::name('shop_group')->where('aid',aid)->column('name','id');
        $groupArr = array_flip($groupArr);
        $fuwuArr = Db::name('shop_fuwu')->where('aid',aid)->column('name','id');
        $fuwuArr = array_flip($fuwuArr);

        //会员级别信息
        $level_lists = Db::name('member_level')->where('aid',aid)->order('id asc')->column('name','id');

        $pagenum = input('pagenum')?:1;
        $pagelimit = input('pagelimit')?:5;
        $start_hange = ($pagenum-1)*$pagelimit+1;
        $end_hang = $pagenum*$pagelimit;
        $insertnum = 0;
        $updatenum = 0;
        Db::startTrans();
        $data_count = count($exceldata);
        //dump($start_hange.'=>'.$end_hang);exit;
        foreach($exceldata as $hang=>$data){
            if($hang+1<$start_hange){
                continue;
            }
            if($hang+1>$end_hang){
                continue;
            }
            if(empty($data[2])){
                continue;
            }
            $indata = [];
            $indata['aid'] = aid;
            $indata['bid'] = bid;
            //商品ID
            $proid = $data[0];
            //不是纯数字的商品ID作为0处理
            if(!is_numeric($proid)){
                $proid = 0;
            }else{
                $indata['id'] = $proid;
            }

            $indata['procode'] = $data[2];//商品编码
            $indata['barcode'] = $data[3];//规格编码
            //商品规格处理
            $guige = [];
            $guige_str = '';
            //颜色
            $guige_k = 0;
            if($data[4]){
                $guige[] = [
                    'k' => $guige_k,
                    'title' => '颜色',
                    'items' => [
                        [
                            'k' => 0,
                            'title' => $data[4],
                        ]
                    ],
                ];
                $guige_str .= $data[4].',';
                $guige_k = $guige_k+1;
            }
            //规格
            if($data[5]){
                $guige[] = [
                    'k' => $guige_k,
                    'title' => '规格',
                    'items' => [
                       [
                           'k' => 0,
                            'title' => $data[5],
                       ]
                    ],
                ];
                $guige_str .= $data[5].',';
                $guige_k = $guige_k+1;
            }
            //其他规格(例：内存|硬盘,16|512)(例：内存:16,硬盘:512)
            if($data[6]){
                $arr = explode(',',$data[6]);
                foreach($arr as $guige_group){
                    $guige_name_arr = explode(':',$guige_group);
                    if(count($guige_name_arr)!=2){
                        return json(['status'=>0,'msg'=>'导入失败，第'.$hang.'行其他规格格式错误']);
                    }
                    $guige[] = [
                        'k' => $guige_k,
                        'title' => $guige_name_arr[0],
                        'items' => [
                            [
                                'k' => 0,
                                'title' => $guige_name_arr[1],
                            ]
                        ],
                    ];
                    $guige_str .= $guige_name_arr[1].',';
                    $guige_k = $guige_k+1;
                }
                unset($k);
            }
            $guige_str = rtrim($guige_str,',');
            //dump($guige_str);
            //dump($guige);
            if($guige){
                $indata['guigedata'] = json_encode($guige,JSON_UNESCAPED_UNICODE);
            }else{
                $indata['guigedata'] = '[{"k":0,"title":"规格","items":[{"k":0,"title":"默认规格"}]}]';;
            }
            //商品图片
            $pics = [];
            $pic_main = '';//产品主图，先取第一个
            if($data[7]){
                //有可能是json格式
                $pics_arr = json_decode($data[7],true);
                if(!$pics_arr){
                    $pics_arr = explode(',',$data[7]);
                }
                foreach($pics_arr as $k=>$v){
                    $pic = $v;
                    if(strpos($pic,'//')===0) $pic = 'https:'.$pic;
                    if($pic){
                        $pic = \app\common\Pic::uploadoss($pic);
                    }
                    if($k==0){
                        $pic_main = $pic;
                    }
                    $pics[] = $pic;
                }
                $indata['pics'] = implode(',',$pics);
                unset($k,$v,$pics);
            }
            //商品详情（图片列表格式）
            $detail = [];
            if($data[8]){
                //有可能是json格式
                $pics_arr = json_decode($data[8],true);
                if(!$pics_arr){
                    $pics_arr = explode(',',$data[8]);
                }
                //转换成富文本格式
                foreach($pics_arr as $k=>$v){
                    $pic = $v;
                    if(strpos($pic,'//')===0) $pic = 'https:'.$pic;
                    if($pic){
                        $pic = \app\common\Pic::uploadoss($pic);
                    }
                    $detail[] = [
                        'id' => 'M000000000000'.$k,
                        'temp' => 'picture',
                        'params' => [
                            'bgcolor'=>'#FFFFFF','margin_x'=>0,'margin_y'=>0,'padding_x'=>0,'padding_y'=>0,'borderradius'=>0,
                            'quanxian' => ['all'=>true],
                            'platform' => ['all'=>true],
                            'mendian' => ['all'=>true],
                            'mendian_sort' => 'sort',
                        ],
                        'data' => [
                            [
                                'id' => 'P0000000000001',
                                'imgurl' => $pic,
                                'hrefurl' => '',
                                'option' => 0
                            ]
                        ],
                        'other' => '',
                        'content' => ''
                    ];
                }
            }
            //商品详情 富文本格式
            if($data[46]){
                $detail[] = [
                    'id'=>'M0000000000000',
                    'temp'=>'richtext',
                    'params'=>['bgcolor'=>'#FFFFFF','margin_x'=>0,'margin_y'=>0,'padding_x'=>0,'padding_y'=>0,'quanxian'=>['all'=>true],'platform'=>['all'=>true],'mendian' => ['all'=>true],
                        'mendian_sort' => 'sort',],
                    'data'=>'',
                    'other'=>'',
                    'content'=>$data[46]
                ];
            }
            if($detail){
                $indata['detail'] = json_encode($detail);
            }
            //规格图片
            $guige_pic = \app\common\Pic::uploadoss($data[9]);

            $indata['name'] = $data[10];//商品名称
            $indata['sellpoint'] = $data[12];//商品卖点
            $indata['product_link'] = $data[14]?:'';//宝贝链接
            $indata['stock'] = intval($data[15]);//库存
            $indata['weight'] = intval($data[16]);//重量
            $indata['sell_price'] = round($data[17],2);//销售价
            $indata['market_price'] = round($data[18],2);//市场价
            $indata['cost_price'] = round($data[19],2);//成本价
            //会员价处理(excel固定了20，21，22，23，24是从低到高的会员价)
            $lvprice_data = [];
            $k = 20;
            foreach($level_lists as $level_id=>$level_name){
                if($k<=24){
                    $level_price = $data[$k];
                }else{
                    $level_price = $data[24];
                }
                if($level_price>0){
                    $lvprice_data[$level_id] = $level_price;
                }
                $k++;
            }
            if($lvprice_data){
                $indata['lvprice'] = 1;
                $indata['lvprice_data'] = $lvprice_data;
            }
            //商品分类
            if($data[25]){
                $cids = [];
                foreach(explode(',',$data[25]) as $v){
                    if(!$cateArr[$v]){
                        if(bid == 0){
                            $cid = Db::name('shop_category')->insertGetId(['aid'=>aid,'name'=>$v,'sort'=>0]);
                            $cids[] = $cid;
                            $cateArr[$v] = $cid;
                        }
                    }else{
                        $cids[] = $cateArr[$v];
                    }
                }
                $indata['cid'] = implode(',',$cids);
            }
            //商品分组
            if($data[26]){
                $gids = [];
                foreach(explode(',',$data[26]) as $v){
                    if(!$groupArr[$v]){
                        if(bid == 0){
                            $gid = Db::name('shop_group')->insertGetId(['aid'=>aid,'name'=>$v,'sort'=>0]);
                            $gids[] = $gid;
                            $groupArr[$v] = $gid;
                        }
                    }else{
                        $gids[] = $groupArr[$v];
                    }
                }
                $indata['gid'] = implode(',',$gids);
            }
            //商品服务
            if($data[27]){
                $fwids = [];
                foreach(explode(',',$data[27]) as $v){
                    if(!$fuwuArr[$v]){
                        $fwid = Db::name('shop_fuwu')->insertGetId(['aid'=>aid,'bid'=>bid,'name'=>$v,'sort'=>0]);
                        $fuwuArr[$v] = $fwid;
                    }else{
                        $fwid = $fuwuArr[$v];
                    }
                    $fwids[] = $fwid;
                }
                $indata['fwid'] = implode(',',$fwids);
            }
            //商品类型
            $product_type = strpos($data[28],'眼镜')===false?0:1;
            $indata['product_type'] = $product_type;
            //配送模板
            $indata['freighttype'] = $data[29];
            if($data[29]==0){
                $indata['freightdata'] = $data[30];
            }
            if($data[29]==3){
                $indata['freightcontent'] = $data[30];
            }
            //分红设置
            $indata['fenhongset'] = $data[31]?:0;
            //团队分红
            $indata['teamfenhongset'] = $data[32]?:4;
            if($data[33]){
                $teamfenhongdata1 = [];
                $teamfenhongdata2 = [];
                $teamfenhong_arr = explode(',',$data[33]);
                foreach($teamfenhong_arr as $teamfenhong_str){
                    $arr = explode(':',$teamfenhong_str);
                    //验证填写的级别是否存在
                    if(empty($level_lists[$arr[0]])){
                        continue;
                    }
                    //单独设置分红比例
                    if($data[32]==1){
                        $teamfenhongdata1[$arr[0]]['commission'] = $arr[1];
                    }elseif($data[32]==2){
                        //单独设置分红金额
                        $teamfenhongdata2[$arr[0]]['commission'] = $arr[1];
                    }elseif($data[32]==3){
                        //单独设置分红积分比例
                        $teamfenhongdata1[$arr[0]]['score'] = $arr[1];
                    }
                }
                $indata['teamfenhongdata1'] = json_encode($teamfenhongdata1);
                $indata['teamfenhongdata2'] = json_encode($teamfenhongdata2);
            }
            //股东分红设置
            $indata['gdfenhongset'] = $data[34]?:0;
            if($data[35]){
                $gdfenhong_arr = explode(',',$data[35]);
                $gdfenhongdata1 = [];
                $gdfenhongdata2 = [];
                foreach($gdfenhong_arr as $gdfenhong_str){
                    $arr = explode(':',$gdfenhong_str);
                    //验证填写的级别是否存在
                    if(empty($level_lists[$arr[0]])){
                        continue;
                    }
                    //单独设置分红比例
                    if($data[34]==1){
                        $gdfenhongdata1[$arr[0]]['commission'] = $arr[1];
                    }elseif($data[34]==2){
                        //单独设置分红金额
                        $gdfenhongdata2[$arr[0]]['commission'] = $arr[1];
                    }elseif($data[34]==3){
                        //单独设置分红积分比例
                        $gdfenhongdata1[$arr[0]]['score'] = $arr[1];
                    }
                }
                $indata['gdfenhongdata1'] = json_encode($gdfenhongdata1);
                $indata['gdfenhongdata2'] = json_encode($gdfenhongdata2);
            }
            //区域代理分红
            $indata['areafenhongset'] = $data[36]?:0;
            if($data[37]){
                $areafenhong_arr = explode(',',$data[37]);
                $areafenhongdata1 = [];
                $areafenhongdata2 = [];
                foreach($areafenhong_arr as $gdfenhong_str){
                    $arr = explode(':',$gdfenhong_str);
                    //验证填写的级别是否存在
                    if(empty($level_lists[$arr[0]])){
                        continue;
                    }
                    //单独设置分红比例
                    if($data[36]==1){
                        $areafenhongdata1[$arr[0]]['commission'] = $arr[1];
                    }elseif($data[36]==2){
                        //单独设置分红金额
                        $areafenhongdata2[$arr[0]]['commission'] = $arr[1];
                    }elseif($data[36]==3){
                        //单独设置分红积分比例
                        $areafenhongdata1[$arr[0]]['score'] = $arr[1];
                    }
                }
                $indata['areafenhongdata1'] = json_encode($areafenhongdata1);
                $indata['areafenhongdata2'] = json_encode($areafenhongdata2);
            }
            //积分抵扣
            $indata['scoredkmaxset'] = $data[38];
            $indata['scoredkmaxval'] = $data[39]?:0;
            //显示条件
            if($data[40]){
                $showtj = implode(',',explode('|',$data[40]));
                $indata['showtj'] = $showtj;
            }
            //购买条件
            if($data[41]){
                $gettj = implode(',',explode('|',$data[41]));
                $indata['gettj'] = $gettj;
            }
            //销量处理

            if($proid){
                $exit_product = Db::name('shop_product')
                    ->where('aid',aid)
                    ->where('bid',bid)
                    ->where('id',$proid)
                    ->find();
            }else{
                $exit_product = Db::name('shop_product')
                    ->where('aid',aid)
                    ->where('bid',bid)
                    ->where('procode',$indata['procode'])
                    ->find();
            }
            //echo Db::getLastSql();
            $sales = intval($data[42]);
            if($exit_product){
                $sales = bcadd($exit_product['sales'],$sales);
            }
            $indata['sales'] = $sales;//销量
            //状态
            if($data[43] == '已上架' || $data[43] == '上架'){
                $indata['status'] = 1;
            }else {
                $indata['status'] = 0;
            }
            $pic_main = $data['44']?:$pic_main;
            if($pic_main){
                $indata['pic'] = $data['44']?:$pic_main;//商品主图
            }
            if($data[45]){
                $indata['video'] = $data[45];//商品视频
            }


            $indata['createtime'] = time();
            if(bid != 0) $indata['commissionset'] = -1;
            //dump($data);
            //dump($indata);exit;
            //商品已存在，修改
            if($exit_product){
                //相同产品，不同规格，重新组织规格数据
                $exit_guige = json_decode($exit_product['guigedata'],true);
                $guige = array_column($guige,null,'title');
                $exit_guige = array_column($exit_guige,null,'title');
                $new_guige = [];
                //dump($guige);
                //dump($exit_guige);
                if($guige && $exit_guige){
                    foreach($guige as $k=>$v){
                        //dump($k.'开始');
                        if(!empty($exit_guige[$k])){
                            $items = array_column($v['items'],'title');
                            $exit_items = array_column($exit_guige[$k]['items'],'title');
                            //dump($items);
                            //dump($exit_items);
                            foreach($items as $item_v){
                                if(!in_array($item_v,$exit_items)){
                                    //dump('加入'.$item_v);
                                    array_push($exit_items,$item_v);
                                }
                            }
                            //dump($exit_items);
                            //$new_items = array_unique(array_merge($exit_items,$items));
                            //dump($exit_items);
                            $new_guige_item = [];
                            foreach($exit_items as $item_k=>$item_title){
                                $new_guige_item[] = ['k'=>$item_k,'title'=>$item_title];
                            }
                            $new_guige[] =  [
                                'k' => $v['k'],
                                'title' => $k,
                                'items' => $new_guige_item,
                            ];


                        }else{
                            return json(['status'=>0,'msg'=>'导入失败，第'.$hang.'行规格格式与相同产品的规格不匹配']);
                        }

                    }
                    $indata['guigedata'] = json_encode($new_guige,JSON_UNESCAPED_UNICODE);
                    //dump($new_guige);
                }


                $proid = $exit_product['id'];
                //dump($indata);
                Db::name('shop_product')->where('id',$proid)->update($indata);
            }else{
                //dump($indata);
                $proid = Db::name('shop_product')->insertGetId($indata);
            }
            //删除相同产品id,相同规格的规格数据
            $same = Db::name('shop_guige')->where('aid',aid)->where('proid',$proid)->where('name',$guige_str)->find();
            $guige_id = 0;
            if($same){
                $guige_id = $same['id'];
            }
            //根据产品表规格数据的顺序排列规格表的ks顺序
            $ks_str = '';
            $guige_arr = explode(',',$guige_str);
            $guige_data = json_decode($indata['guigedata'],true);
            foreach($guige_data as $guige_k=>$guige_v){
                $title = $guige_arr[$guige_k];
                $item_titles = array_column($guige_v['items'],'title');
                $ks = array_search($title,$item_titles);
                $ks_str .= $ks.',';
            }
            $ks_str = rtrim($ks_str,',');

            //dump($ks_str);
            //var_dump($ks_str);exit;
            $ggdata = [];
            $ggdata['aid'] = aid;
            $ggdata['proid'] = $proid;
            $ggdata['procode'] = $data[2];
            $ggdata['barcode'] = $data[3];
            $ggdata['name'] = $guige_str;
            $ggdata['ks'] = $ks_str;
            $ggdata['pic'] = $guige_pic;
            $ggdata['cost_price'] = $indata['cost_price'];
            $ggdata['market_price'] = $indata['market_price'];
            $ggdata['sell_price'] = $indata['sell_price'];
            $ggdata['stock'] = $indata['stock'];
            $ggdata['weight'] = $indata['weight'];
            //会员价
            $ggdata['lvprice_data'] = json_encode($lvprice_data);

            //dump($ggdata);exit;
            if($guige_id){
                Db::name('shop_guige')->where('id',$guige_id)->update($ggdata);
            }else{
                Db::name('shop_guige')->insert($ggdata);
            }


            $insertnum++;
        }
        //die('stop');
        Db::commit();
        \app\common\System::plog('导入商品');
        $suc_total = $pagelimit*($pagenum-1)+$insertnum;
        $status = 1;
        if($suc_total>=$data_count){
            $status = 2;
        }
        $remain = $data_count-$suc_total;
        return json(['status'=>$status,'msg'=>'成功导入'.$suc_total.'条数据,剩余'.$remain]);
    }

    //导出
    public function excel(){

        if(input('param.field') && input('param.order')){
            $order = input('param.field').' '.input('param.order');
        }else{
            $order = 'sort desc,id desc';
        }
        $where = array();
        $where[] = ['s.aid','=',aid];
        if(bid==0){
            if(input('param.bid')){
                $where[] = ['s.bid','=',input('param.bid')];
            }elseif(input('param.showtype')==2){
                $where[] = ['s.bid','>',0];
                $where[] = ['s.linkid','=',0];
            }elseif(input('param.showtype')=='all'){
                $where[] = ['s.bid','>=',0];
            }elseif(input('param.showtype')==21){
                $where[] = ['s.bid','=',-1];
            }else{
                $where[] = ['bid','=',0];
            }
        }else{
            $where[] = ['s.bid','=',bid];
        }
        if(input('ids')){
            $where[] = ['s.id','in',input('ids')];
        }
        $where[] = ['douyin_product_id','=',''];
        if(input('?param.ischecked') && input('param.ischecked')!=='') $where[] = ['s.ischecked','=',$_GET['ischecked']];
        if(input('param.name')) $where[] = ['s.name','like','%'.input('name').'%'];
        if(input('?param.status') && input('param.status')!==''){
            $status = input('param.status');
            $nowtime = time();
            $nowhm = date('H:i');
            if($status==1){
                $where[] = Db::raw("`status`=1 or (`status`=2 and unix_timestamp(start_time)<=$nowtime and unix_timestamp(end_time)>=$nowtime) or (`status`=3 and ((start_hours<end_hours and start_hours<='$nowhm' and end_hours>='$nowhm') or (start_hours>=end_hours and (start_hours<='$nowhm' or end_hours>='$nowhm'))) )");
            }else{
                $where[] = Db::raw("`status`=0 or (`status`=2 and (unix_timestamp(start_time)>$nowtime or unix_timestamp(end_time)<$nowtime)) or (`status`=3 and ((start_hours<end_hours and (start_hours>'$nowhm' or end_hours<'$nowhm')) or (start_hours>=end_hours and (start_hours>'$nowhm' and end_hours<'$nowhm'))) )");
            }
        }
        if(input('?param.cid') && input('param.cid')!==''){
            $cid = input('param.cid');
            //子分类
            $clist = Db::name('shop_category')->where('aid',aid)->where('pid',$cid)->column('id');
            if($clist){
                $clist2 = Db::name('shop_category')->where('aid',aid)->where('pid','in',$clist)->column('id');
                $cCate = array_merge($clist, $clist2, [$cid]);
                if($cCate){
                    $whereCid = [];
                    foreach($cCate as $k => $c2){
                        $whereCid[] = "find_in_set({$c2},cid)";
                    }
                    $where[] = Db::raw(implode(' or ',$whereCid));
                }
            } else {
                $where[] = Db::raw("find_in_set(".$cid.",cid)");
            }
        }
        if(input('?param.cid2') && input('param.cid2')!==''){
            $cid = input('param.cid2');
            //子分类
            $clist = Db::name('shop_category2')->where('aid',aid)->where('pid',$cid)->column('id');
            if($clist){
                $clist2 = Db::name('shop_category2')->where('aid',aid)->where('pid','in',$clist)->column('id');
                $cCate = array_merge($clist, $clist2, [$cid]);
                if($cCate){
                    $whereCid = [];
                    foreach($cCate as $k => $c2){
                        $whereCid[] = "find_in_set({$c2},cid2)";
                    }
                    $where[] = Db::raw(implode(' or ',$whereCid));
                }
            } else {
                $where[] = Db::raw("find_in_set(".$cid.",cid2)");
            }
        }
        if(input('?param.gid') && input('param.gid')!=='') $where[] = Db::raw("find_in_set(".input('param.gid/d').",gid)");

        if(input('?param.wxvideo_status') && input('param.wxvideo_status')!==''){
            if(input('param.wxvideo_status') < 5){
                if(input('param.wxvideo_status') == 0){
                    $where[] = ['wxvideo_product_id','=',''];
                }else{
                    $where[] = ['wxvideo_edit_status','=',input('param.wxvideo_status')];
                }
            }else{
                $where[] = ['wxvideo_status','=',input('param.wxvideo_status')];
            }
        }
        $field = 's.id,s.procode,g.barcode,g.name guige_name,s.pics,s.detail,g.pic guige_pic,s.name,s.sellpoint,s.product_link,g.stock,g.weight,g.sell_price,g.market_price
            ,g.cost_price,g.lvprice_data,s.cid,s.gid,s.fwid,s.product_type,s.freighttype,s.freightdata,s.freightcontent,s.fenhongset,s.teamfenhongset,s.teamfenhongdata1
            ,s.teamfenhongdata2,s.gdfenhongset,s.gdfenhongdata1,s.gdfenhongdata2,s.areafenhongset,s.areafenhongdata1,s.areafenhongdata2,s.scoredkmaxset,s.scoredkmaxval
            ,s.showtj,s.gettj,g.sales,s.status,s.start_time,s.end_time,s.start_hours,s.end_hours,s.pic,s.video,s.guigedata';
        $list = Db::name('shop_product')
            ->alias('s')
            ->join('shop_guige g','s.id=g.proid','left')
            ->where($where)->order($order)->field($field)->select()->toArray();
        //echo Db::getlastSql();
        //dump($list);exit;

        foreach($list as $k=>$v){
            $gglist = Db::name('shop_guige')->where('aid',aid)->where('proid',$v['id'])->select()->toArray();
            $ggdata = array();
            foreach($gglist as $gg){
                $ggdata[] = $gg['name'].' × '.$gg['stock'] .' <button class="layui-btn layui-btn-xs layui-btn-disabled" style="color:#333">￥'.$gg['sell_price'].'</button>';
            }
            $list[$k]['ggdata'] = implode('<br>',$ggdata);
            $list[$k]['realsalenum'] = Db::name('shop_order_goods')->where('aid',aid)->where('proid',$v['id'])->where('status','in','1,2,3')->sum('num');
            if($v['status']==2){ //设置上架时间
                if(strtotime($v['start_time']) <= time() && strtotime($v['end_time']) >= time()){
                    $list[$k]['status'] = 1;
                }else{
                    $list[$k]['status'] = 0;
                }
            }
            if($v['status']==3){ //设置上架周期
                $start_time = strtotime(date('Y-m-d '.$v['start_hours']));
                $end_time = strtotime(date('Y-m-d '.$v['end_hours']));
                if(($start_time < $end_time && $start_time <= time() && $end_time >= time()) || ($start_time >= $end_time && ($start_time <= time() || $end_time >= time()))){
                    $list[$k]['status'] = 1;
                }else{
                    $list[$k]['status'] = 0;
                }
            }
            if($v['bid'] == -1) $data[$k]['sort'] = $v['sort'] - 1000000;
        }
        //dump($list);
        $title = ["商品ID","明细ID","商品编码","规格编码","颜色","规格","其他规格","商品图片","商品详情（图片列表）","规格图片","商品名称","SKU商品简称","商品卖点","商品描述","宝贝链接","库存",
            "重量","销售价","市场价","成本价","1级供货价","2级供货价","3级供货价","4级供货价","5级供货价","商品分类","商品分组","商品服务","商品类型","配送模板类型","模板信息","分红设置",
            "团队分红设置","团队分红比例","股东分红设置","股东分红比例","区域代理分红设置","区域代理分红比例","积分抵扣设置","积分抵扣设置比例","显示条件","购买条件","销量",
            "状态","商品主图","商品视频","商品详情（富文本）"
        ];
        $data = array();
        foreach($list as $k=>$vo){
            //商品分类
            if(bid > 0){
                $cateArr = Db::name('shop_category2')->Field('id,name')->where('aid',aid)
                    ->where('bid',bid)->whereIn('id',$vo['cid'])->column('name');
            }else{
                $cateArr = Db::name('shop_category')->where('aid',aid)->whereIn('id',$vo['cid'])->column('name');
            }

            $cnames = implode(',',$cateArr);
            //商品分组
            if($vo['gid']){
                $groupArr = Db::name('shop_group')->where('aid',aid)->whereIn('id',$vo['gid'])->column('name');
                $group_names = implode(',',$groupArr);
            }
            //商品服务
            if($vo['fwid']){
                $fuwuArr = Db::name('shop_fuwu')->where('aid',aid)->whereIn('id',$vo['fwid'])->column('name');
                $fw_names = implode(',',$fuwuArr);
            }
            //商品类型
            $product_type_name = $vo['product_type']==1?'2.眼镜商品':'1.普通商品';
            //模板信息
            $freightdata = '';
            if($vo['freighttype']==0){
                $freightdata = $vo['freightdata'] ;
            }
            if($vo['freighttype']==3){
                $freightdata = $vo['freightcontent'] ;
            }
            //团队分红
            $teamfenhongdata = $vo['teamfenhongdata1'];
            if( $vo['teamfenhongset']==2){
                $teamfenhongdata = $vo['teamfenhongdata2'];
            }
            $teamfenhongdata = json_decode($teamfenhongdata,true);
            $teamfenhongdata_str = '';
            foreach($teamfenhongdata as $team_level=>$team_data){
                if($team_data['score']>0){
                    $commission = $team_data['score'];
                }else{
                    $commission = $team_data['commission']?:'0';
                }
                $teamfenhongdata_str .= $team_level.':'.$commission.',';
            }
            $teamfenhongdata_str = rtrim($teamfenhongdata_str,',');
            //股东分红
             $gdfenhongdata = $vo['gdfenhongdata1'];
            if( $vo['gdfenhongset']==2){
                $gdfenhongdata = $vo['gdfenhongdata2'];
            }
            $gdfenhongdata = json_decode($gdfenhongdata,true);
            $gdfenhongdata_str = '';
            foreach($gdfenhongdata as $gudong_level=>$gudong_data){
                if($gudong_data['score']>0){
                    $commission = $gudong_data['score'];
                }else{
                    $commission = $gudong_data['commission']?:'0';
                }
                $gdfenhongdata_str .= $gudong_level.':'.$commission.',';
            }
            $gdfenhongdata_str = rtrim($gdfenhongdata_str,',');
            //区域代理分红
            $areafenhongdata = $vo['areafenhongdata1'];
            if( $vo['areafenhongset']==2){
                $areafenhongdata = $vo['areafenhongdata2'];
            }
            $areafenhongdata = json_decode($areafenhongdata,true);
            $areafenhongdata_str = '';
            foreach($areafenhongdata as $area_level=>$area_data){
                if($area_data['score']>0){
                    $commission = $area_data['score'];
                }else{
                    $commission = $area_data['commission']?:'0';
                }
                $areafenhongdata_str .= $area_level.':'.$commission.',';
            }
            $areafenhongdata_str = rtrim($areafenhongdata_str,',');
            //状态
            $status_str = $vo['status']==1?'已上架':'已下架';
            //商品详情
            $detail = json_decode($vo['detail'],true);
            $detail_pics = [];
            $detail_content = '';
            foreach($detail as $d_k=>$d_v){
                if($d_v['temp']=='picture' || $d_v['temp']=='pictures'){
                    foreach($d_v['data'] as $data_v){
                        $detail_pics[] = $data_v['imgurl'];
                    }
                }elseif($d_v['temp']=='richtext'){
                    $detail_content = $d_v['content'];
                    $pattern ="/<img .*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png|\.jpeg]))[\'|\"].*?[\/]?>/";
                    preg_match_all($pattern,$detail_content,$match);
                    if(isset($match[1])&&!empty($match[1])) {
                        $detail_pics = array_merge($detail_pics,$match[1]);
                    }
                }
            }
            $detail_pics = json_encode($detail_pics,JSON_UNESCAPED_SLASHES);
            //级别价格
            $lvprice_arr = json_decode($vo['lvprice_data'],true);
            $lvprice_arr = array_values($lvprice_arr);
            //规格处理
            $guige_yanse = '';
            $guige_guige = '';
            $guige_qita = '';
            $guigedata = json_decode($vo['guigedata'],true);
            $guige_name_arr = explode(',',$vo['guige_name']);
            foreach($guigedata as $g_k=>$g_v){
                if($g_v['title']=='颜色'){
                    $guige_yanse = $guige_name_arr[$g_v['k']];
                }elseif($g_v['title']=='规格'){
                    $guige_guige = $guige_name_arr[$g_v['k']];
                }else{
                    $guige_qita .= $g_v['title'].':'.$guige_name_arr[$g_v['k']].',';
                }
            }
            $guige_qita = rtrim($guige_qita,',');

            //商品图片
            $pics = json_encode(explode(',',$vo['pics']),JSON_UNESCAPED_SLASHES);
            //显示条件
            $showtj = implode('|',explode(',',$vo['showtj']));
            //购买条件
            $gettj = implode('|',explode(',',$vo['gettj']));

            $data[] = [
                $vo['id'],
                '',//明细ID
                $vo['procode'],//商品编码
                $vo['barcode'],//规格编码
                $guige_yanse,//颜色 todo
                $guige_guige,//规格 todo
                $guige_qita,//其他规格 todo
                $pics,//商品图片
                $detail_pics,//商品详情（图片列表）
                $vo['guige_pic'],//规格图片
                $vo['name'],//商品名称
                '',//SKU商品简称
                $vo['sellpoint'],//商品卖点
                '',//商品描述
                $vo['product_link'],//宝贝链接
                $vo['stock'],//库存
                $vo['weight'],//重量
                $vo['sell_price'],//销售价
                $vo['market_price'],//市场价
                $vo['cost_price'],//成本价
                $lvprice_arr[0],//1级供货价
                $lvprice_arr[1],//2级供货价
                $lvprice_arr[2],//3级供货价
                $lvprice_arr[3],//4级供货价
                $lvprice_arr[4],//5级供货价
                $cnames,//商品分类
                $group_names,//商品分组
                $fw_names,//商品服务
                $product_type_name,//商品类型
                $vo['freighttype'],//配送模板类型
                $freightdata,//模板信息
                $vo['fenhongset'],//分红设置
                $vo['teamfenhongset'],//团队分红设置
                $teamfenhongdata_str,//团队分红比例
                $vo['gdfenhongset'],//股东分红设置
                $gdfenhongdata_str,//股东分红比例
                $vo['areafenhongset'],//区域代理分红设置
                $areafenhongdata_str,//区域代理分红比例
                $vo['scoredkmaxset'],//积分抵扣设置
                $vo['scoredkmaxval'],//积分抵扣设置比例
                $showtj,//显示条件
                $gettj,//购买条件
                $vo['sales'],//销量
                $status_str,//状态
                $vo['pic'],//商品主图
                $vo['video'],//商品视频
                $detail_content,//商品详情（富文本）
            ];
        }
        //dump($data);exit;
        $this->export_excel($title,$data);
    }

    public function editManyCategory(){
        }

    //编辑商品
    public function edit2(){
        if(input('param.id')){
            $info = Db::name('shop_product')->where('aid',aid)->where('id',input('param.id/d'))->find();
            if(!$info) showmsg('商品不存在');
            if(bid != 0 && $info['bid']!=bid) showmsg('无权限操作');
            if(bid != 0 && $info['linkid']!=0 && !getcustom('business_copy_product')) showmsg('无权限操作');
        }

        $usdrate = '0';
        //多规格
        $newgglist = array();
        if($info){
            $gglist = Db::name('shop_guige')->where('aid',aid)->where('proid',$info['id'])->select()->toArray();
            foreach($gglist as $k=>$v){
                $v['lvprice_data'] = json_decode($v['lvprice_data']);
                if($v['ks']!==null){
                    $newgglist[$v['ks']] = $v;
                }else{
                    Db::name('shop_guige')->where('aid',aid)->where('id',$v['id'])->update(['ks'=>$k]);
                    $newgglist[$k] = $v;
                }
            }
        }
        //分类
        $clist = Db::name('shop_category')->Field('id,name')->where('aid',aid)->where('pid',0)->order('sort desc,id')->select()->toArray();
        foreach($clist as $k=>$v){
            $child = Db::name('shop_category')->Field('id,name')->where('aid',aid)->where('pid',$v['id'])->order('sort desc,id')->select()->toArray();
            foreach($child as $k2=>$v2){
                $child2 = Db::name('shop_category')->Field('id,name')->where('aid',aid)->where('pid',$v2['id'])->order('sort desc,id')->select()->toArray();
                $child[$k2]['child'] = $child2;
            }
            $clist[$k]['child'] = $child;
        }
        if(bid > 0){
            //商家的分类
            $clist2 = Db::name('shop_category2')->Field('id,name')->where('aid',aid)->where('bid',bid)->where('pid',0)->order('sort desc,id')->select()->toArray();
            foreach($clist2 as $k=>$v){
                $child = Db::name('shop_category2')->Field('id,name')->where('aid',aid)->where('bid',bid)->where('pid',$v['id'])->order('sort desc,id')->select()->toArray();
                foreach($child as $k2=>$v2){
                    $child2 = Db::name('shop_category2')->Field('id,name')->where('aid',aid)->where('bid',bid)->where('pid',$v2['id'])->order('sort desc,id')->select()->toArray();
                    $child[$k2]['child'] = $child2;
                }
                $clist2[$k]['child'] = $child;
            }
        }
        //分组
        $glist = Db::name('shop_group')->where('aid',aid)->order('sort desc,id')->select()->toArray();
        $freightdata = array();
        if($info && $info['freightdata']){
            $freightdata = Db::name('freight')->where('aid',aid)->where('id','in',$info['freightdata'])->order('sort desc,id')->select()->toArray();
        }

        $weightdata = array();
        $bset = Db::name('business_sysset')->where('aid',aid)->find();
        //分成结算类型
        $sysset = Db::name('admin_set')->where('aid',aid)->find();
        if($sysset['fxjiesuantype'] == 1) {
            $jiesuantypeDesc = '成交价';
        }elseif($sysset['fxjiesuantype'] == 2) {
            $jiesuantypeDesc = '销售利润';
        } else {
            $jiesuantypeDesc = '销售价';
        }

        $info['showtj'] = explode(',',$info['showtj']);
        $info['gettj'] = explode(',',$info['gettj']);
        $info['cid'] = explode(',',$info['cid']);
        $info['cid2'] = explode(',',$info['cid2']);
        $info['commission_mid'] = $info['commission_mid'] ? json_decode($info['commission_mid'],true) : [];
        if($info['bid'] == -1) $info['sort'] = $info['sort'] - 1000000;
        $default_cid = Db::name('member_level_category')->where('aid',aid)->where('isdefault', 1)->value('id');
        $default_cid = $default_cid ? $default_cid : 0;
        if(false){}else {
            $aglevellist = Db::name('member_level')->where('aid',aid)->where('cid', $default_cid)->where('can_agent','<>',0)->order('sort,id')->select()->toArray();
            $levellist = Db::name('member_level')->where('aid',aid)->where('cid', $default_cid)->order('sort,id')->select()->toArray();
        }
        $gdlevellist = Db::name('member_level')->where('aid',aid)->where('cid', $default_cid)->where('fenhong','>','0')->order('sort,id')->select()->toArray();
        $teamlevellist = Db::name('member_level')->where('aid',aid)->where('cid', $default_cid)->where('teamfenhonglv','>','0')->order('sort,id')->select()->toArray();
        $areafhlevellist = Db::name('member_level')->where('aid',aid)->where('areafenhong','>','0')->select()->toArray();

        if($info['id']){
            $fuwulist = Db::name('shop_fuwu')->where('aid',aid)->where('bid',$info['bid'])->order('sort desc,id')->select()->toArray();
        }else{
            $fuwulist = Db::name('shop_fuwu')->where('aid',aid)->where('bid',bid)->order('sort desc,id')->select()->toArray();
        }
        //商品参数
        $parambid = bid;
        $whereParam = [];
        $whereParam[] = ['aid','=',aid];
        $whereParam[] = ['status','=',1];
        if($info['cid']){
            $whereCid = [];
            foreach($info['cid'] as $k => $c2){
                if($c2 == '') continue;
                $whereCid[] = "find_in_set({$c2},cid)";
            }
            if($whereCid){
                if(false){}else{
                    $whereParam[] = ['bid','=',$parambid];
                    $whereParam[] = Db::raw(implode(' or ',$whereCid). " or cid =''");
                }
            }else{
                $whereParam[] = ['bid','=',$parambid];
                $whereParam[] = Db::raw("cid =''");
            }
        }else{
            $whereParam[] = ['bid','=',$parambid];
            $whereParam[] = Db::raw(" cid =''");
        }
        $paramList = Db::name('shop_param')->where($whereParam)->order('sort desc,id')->select()->toArray();
//        dd($paramList);
        View::assign('paramList',$paramList);



        $paramdata = $info['paramdata'] ? json_decode($info['paramdata'],true) : [];
//        dd($paramdata);
        $auth = [];
        $info['paramdata'] = str_ireplace("'", "\'", $info['paramdata']);
        View::assign('fuwulist',$fuwulist);
        View::assign('aglevellist',$aglevellist);
        View::assign('levellist',$levellist);
        View::assign('gdlevellist',$gdlevellist);
        View::assign('teamlevellist',$teamlevellist);
        View::assign('areafhlevellist',$areafhlevellist);
        View::assign('info',$info);
        View::assign('newgglist',$newgglist);
        View::assign('clist',$clist);
        View::assign('clist2',$clist2);
        View::assign('glist',$glist);
        View::assign('freightdata',$freightdata);
        View::assign('bset',$bset);
        View::assign('jiesuantypeDesc',$jiesuantypeDesc);
        View::assign('paramdata',$paramdata);
        $fromwxvideo = input('param.fromwxvideo')==1?true:false;

        if($fromwxvideo){
            $rs = curl_post('https://api.weixin.qq.com/shop/account/get_brand_list?access_token='.Wechat::access_token(aid,'wx'),'{}');
            $rs = json_decode($rs,true);
            $brand_list = $rs['data'];
        }else{
            $brand_list = [];
        }
        $brand_list[] = ['brand_id'=>2100000000,'brand_wording'=>'无品牌'];
        View::assign('brand_list',$brand_list);
        View::assign('fromwxvideo',$fromwxvideo);
        View::assign('auth',$auth);

        $business_selfscore = 0;
        View::assign('business_selfscore',$business_selfscore);

        return View::fetch();
    }

	public function mendian_hexiao_set(){
		$proid = input('param.proid');
		if(request()->isAjax()){
			}
		$datalist = Db::name('shop_product_mendian_hexiaoset')->where('aid',aid)->where('bid',bid)->where('proid',$proid)->select()->toArray();
		if($datalist){
			foreach($datalist as &$d){
				$mendian = Db::name('mendian')->field('name')->where('id',$d['mdid'])->find();
				$d['name'] = $mendian['name'];
			}
		}else{
			$product = Db::name('shop_product')->field('bind_mendian_ids')->where('id',$proid)->find();
			$where = [];
			$where[] = ['aid','=',aid];
			if($product['bind_mendian_ids']!='-1'){
				$bind_mendian_ids = explode(',',$product['bind_mendian_ids']);
				$where[] = ['id','in',$bind_mendian_ids];
			}else{
				if($product['bid']==0){
					$bids = Db::name('business')->where('aid',aid)->where('isplatform_auth',1)->where('status',1)->column('id');	
					array_push($bids,$product['bid']);
					$where[] = ['bid','in',$bids];
				}else{
					$where[] = ['bid','=',$product['bid']];
				}
			}	
			$datalist = Db::name('mendian')->field('id,name')->where($where)->select()->toArray();
			foreach($datalist as &$mendian){
				$mendian['mdid'] = $mendian['id'];
				$mendian['hexiaogivepercent'] = 0;
				$mendian['hexiaogivemoney'] = 0;
			}
		}

		View::assign('datalist',$datalist);
		View::assign('proid',$proid);
		return View::fetch();
	}
}
